package com.sunlands.zlcx.usercenter.service.status;

import com.alibaba.fastjson.JSONObject;
import com.sunlands.zlcx.usercenter.constant.LearningStatus;
import com.sunlands.zlcx.usercenter.constant.RedisKeyConst;
import com.sunlands.zlcx.usercenter.domain.LearnContentDO;
import com.sunlands.zlcx.usercenter.domain.UsersTargetRelationDO;
import com.sunlands.zlcx.usercenter.service.status.common.AbstractStudyStatus;
import com.sunlands.zlcx.usercenter.util.BeanPropertiesUtil;
import com.sunlands.zlcx.usercenter.vo.UsersStudyInfoVO;
import com.sunlands.zlcx.usercenter.vo.UsersVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author gaoyanfeng
 * @create 2019-04-28 9:50
 **/
@Component
@Slf4j
public class OrdernaryLearnContinue extends AbstractStudyStatus implements BeanPropertiesUtil {
    @Override
    public void handle(UsersStudyInfoVO usersStudyInfoVO, UsersTargetRelationDO usersTargetRelationDO) {
        Long userId = usersTargetRelationDO.getUserId();
            usersStudyInfoVO.setContinueTime(new Date());
            checkContinuePeriod(usersStudyInfoVO.getContinueTime(), userId);
            usersService.updateStatus(userId, LearningStatus.LEARN_TIMING_CONINUE.getCode(), usersStudyInfoVO.getStartTime(), null, null);
            if(Objects.nonNull(usersStudyInfoVO.getContentId())){
                LearnContentDO contentDO = usersLearnService.findOne(usersStudyInfoVO.getContentId());
                contentDO.setStatus(LearningStatus.LEARN_TIMING_CONINUE.getCode());
                usersLearnService.update(contentDO);
                if(contentDO.getModel().intValue() == LearnContentDO.ModelEnum.valid.code.intValue()){
                    JSONObject jsonObject = usersStudyService.getLearnTimeByUserId(userId);
                    //已学习时长，秒
                    Long learnTime = jsonObject.getLong("learnTime");
                    usersLearnService.schedeledTask(contentDO, (contentDO.getMinutes()-5)*60L - learnTime);
                }
            }
            String continueKey = RedisKeyConst.getContinueLearnTimeByUserid(userId);
            redisTemplate.opsForList().leftPush(continueKey, usersStudyInfoVO.getContinueTime());

    }

    private void checkContinuePeriod(Date continueTime, Long userId) {
        if (null == continueTime) {
            throw new IllegalArgumentException("继续时间不能为空");
        }
        UsersVO usersVO = usersService.findOne(userId);
        if (LearningStatus.getLearningStatus(usersVO.getStatus()) != LearningStatus.LEARN_TIMING_PAUSE) {
            throw new IllegalArgumentException("当前用户状态不是暂停中");
        }
        Date lastLearningEndTime = usersLearnTimingRepository.getLastLearningEndTime(userId);
        if (null != lastLearningEndTime && continueTime.getTime() < lastLearningEndTime.getTime()) {
            throw new IllegalArgumentException("继续时间小于上次学习结束时间");
        }
    }
}
